<template>
  <div style="height: 88%">
    <el-table class="ELtable" ref="tableRef" :data="tableData" style="width: 100%;height:100%;" :row-key="getRowKey"
      default-expand-all>
      <el-table-column prop="keyName" label="参数名称" width="350">
        <template #default="{ row }">
          <el-autocomplete v-if="editor === true && row.keyType !== 'object'" v-model="row.keyName"
            :fetch-suggestions="querySearch" class="inline-input" placeholder=""
            @change="(val) => handleChangeValue(val, row)" @select="(val) => selectSuggestion(val, row)" />
        </template>
      </el-table-column>
      <el-table-column prop="keyType" label="类型">
        <template #default="{ row }">
          <div class="input-wrap" v-if="editor === true">
            <el-select v-model="row.keyType" @change="(val) => handleChangeValue(val, row)">
              <el-option label="string" value="string" />
              <el-option label="integer" value="integer" />
              <el-option label="boolean" value="boolean" />
              <el-option label="number" value="number" />
              <el-option label="array" value="array" />
              <el-option label="object" value="object" />
              <el-option label="null" value="null" />
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="enable" label="是否必需" align="center" v-if="isenable === true">
        <template #default="{ row }">
          <el-checkbox v-model="row.enable" :disabled="editor === false"
            @change="(val) => handleChangeValue(val, row)" />
        </template>
      </el-table-column>
      <el-table-column prop="keyValue" label="参数值">
        <template #default="{ row }">
          <el-input v-model="row.keyValue" @change="(val) => handleChangeValue(val, row)"
            v-if="editor === true && row.keyType !== 'object' && row.keyType !== 'array'" />
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述">
        <template #default="{ row }">
          <el-input v-model="row.description" @change="(val) => handleChangeValue(val, row)" v-if="editor === true">
            <template #suffix>
              <el-icon style="cursor:pointer" @click="openMarkdown(row)">
                <FullScreen />
              </el-icon>
            </template>
          </el-input>
          <v-md-preview v-else :text="row.description" />
        </template>
      </el-table-column>
      <el-table-column width="80" align="center" v-if="editor === true">
        <template #header>
          <span style="color:#409eff;cursor: pointer;" @click="handleMultipleEdit">批量编辑</span>
        </template>
        <template #default="{ row }">
          <el-button link @click="addRowChildren(row)" v-if="row.keyType == 'object' || row.keyType == 'array'">
            <el-tooltip effect="dark" content="添加子字段" placement="top">
              <el-icon>
                <CirclePlus />
              </el-icon>
            </el-tooltip>
          </el-button>
          <el-button link @click="removeRow(row)" v-if="row.keyName !== 'root'">
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-icon>
                <Remove />
              </el-icon>
            </el-tooltip>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <multipleEdit ref="multipleEditRef" :editorValue="editorValue" @update-editor-value="updateEditorValue"
    :isShowText="false" />
    <markdownDialog ref="markdownDialogRef" :data="DescValue" @markdown-value="handleMarkdownValue" />
</template>

<script setup lang="ts">
import {
  Remove, CirclePlus
} from '@element-plus/icons-vue'
import { propTypes } from '@/utils/propTypes'
import multipleEdit from '../debug/dialog/MultipleEdit.vue'
import markdownDialog from './markdownDialog.vue'
import { FullScreen } from '@element-plus/icons-vue'
const tableData = ref([{ id: 1, keyName: 'root', keyValue: '', keyType: 'object', suggestionsVisible: false, enable: false }])
let id = 1000
const tableRef = ref()
const emit = defineEmits(['changeEditMethod', 'selectedTableData', 'tableData']) // 定义 success 事件，用于操作成功后的回调
const props = defineProps({
  data: {
    default: () => [] as any
  },
  editor: propTypes.bool.def(),
  isenable: propTypes.bool.def()
})
const multipleEditRef = ref()
const editorValue = ref()
const currentMultipleEditorRow = ref()
watch(() => props.data,
  () => {
    // 批量编辑后更新表格数据并处理选中
    if (props.data) {
      tableData.value = props.data
      nextTick(() => {
        tableData.value.forEach(item => {
          tableRef.value.toggleRowSelection(item, true)
        })
      })
    }
  }, {
  deep: true
})
import { useDebugStore } from '@/store/modules/debug'
const environmentVars = computed(() => debugStore.getEnvironmentVars)
const debugStore = useDebugStore()
/** 变量名称提示集合 */
const suggestions = computed(() => {
  return environmentVars.value.map(item => {
    return {
      value: item.varName
    }
  })
})
/**建议过滤*/
const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? suggestions.value.filter(createFilter(queryString))
    : suggestions.value
  cb(results)
}
const createFilter = (queryString: string) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}
/**
 * 选择建议
 * */
const selectSuggestion = (val, row?) => {
  // 选择变量名称后，自动补全变量值
  if (val.value.indexOf('{') == -1) {
    const localValue = environmentVars.value.find(e => e.varName == val.value).localValue
    row.keyValue = `{{${localValue}}}`
  }
  handleChangeValue(val, row)
}
/**
 * editor 弹窗值输入完成确定后
 * */
const updateEditorValue = (data) => {
  tableData.value.forEach(item => {
    if (item.id == currentMultipleEditorRow.value.id) {
      item.keyValue = data
    }
  })
}
/**
 * 表单内容变化时自动增加一行
 * */
const handleChangeValue = (val?, row?) => {
  // keyType赋默认值
  row && (row.keyType = row.keyType || 'string')
  updateSelectData()
}
/**
 * 表格数据变化时，更新选中数据
 * */
const updateSelectData = () => {
  // tableData.value.forEach(item => {
  //   const current = tableData.value.find(k => k.id == item.id)
  //   if (current) {
  //     item.id = current.id
  //     item.keyName = current.keyName
  //     item.keyValue = current.keyValue
  //     item.keyType = current.keyType
  //     item.suggestionsVisible = current.suggestionsVisible
  //     item.enable = current.enable
  //   }
  // })
  emit('tableData', tableData.value)
}
/**
 * 获取表格每行的key
 * */
const getRowKey = (row) => {
  return row.id;
}

/**
 * 添加子字段
 * */
const addRowChildren = (data) => {
  let obj = { id: ++id, keyName: '', keyValue: '', keyType: '', suggestionsVisible: false, enable: false }
  if (data.keyType === 'array') {
    if (data.children) {
      obj = { id: ++id, keyName: data.children.length, keyValue: '', keyType: '', suggestionsVisible: false, enable: false }
    } else {
      obj = { id: ++id, keyName: '0', keyValue: '', keyType: '', suggestionsVisible: false, enable: false }
    }
  }
  let node = addNode(tableData.value, data.id, obj)
  tableData.value = node

}
const addNode = (list, pid, obj) => {
  list.forEach((e) => {
    if (e.id == pid) {
      e.children ? e.children.push(obj) : (e.children = [obj])
    } else {
      if (e.children && e.children.length > 0) {
        addNode(e.children, pid, obj)
      }
    }
  })
  return list
}
/**
 * 移除一行
 * */
const removeRow = (row) => {
  let node = removeItem(tableData.value, row.id)
  tableData.value = node
  emit('tableData', tableData.value)
}
const removeItem = (root, id) => {
  root.forEach((e, i) => {
    if (e.id === id) {
      root.splice(i, 1)
    } else if (e.children && e.children.length > 0) {
      removeItem(e.children, id)
    }
  })
  return root
}

/**
 * 点击批量编辑，弹窗
 * */
const handleMultipleEdit = () => {
  emit('changeEditMethod', tableData.value)
}

const markdownDialogRef = ref()
const DescValue = ref('')
const openMarkdown = (row) => {
  currentMultipleEditorRow.value = row
  DescValue.value = row.description
  markdownDialogRef.value.open()
}
const handleMarkdownValue = (data) => {
  tableData.value.forEach(item => {
    if (item.id == currentMultipleEditorRow.value.id) {
      item.description = JSON.parse(JSON.stringify(data.value))
    }
  })
  handleChangeValue()
}

onMounted(() => {
  nextTick(() => {
    tableData.value = props.data
    emit('tableData', tableData.value)
  })
});
</script>

<style scoped>
:deep(.el-table__inner-wrapper::before) {
  height: 0;
}

:deep(th.el-table__cell) {
  font-weight: 400;
  /* color: #000; */
}

.input-wrap {
  position: relative;

  &:hover {
    .array-icon {
      display: block;
    }
  }

  :deep(.upload-demo) {
    position: relative;
    top: 5px;
  }
}

.array-icon {
  position: absolute;
  top: 8px;
  right: 5px;
  display: none;
}


.suggestion-ul {
  list-style: none;
  padding: 0;
  margin: 0;
  line-height: 25px;
}

.hide {
  display: flex;
  width: 100%;
  height: 0;
  line-height: 0;
}

:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  box-shadow: none;
  border-radius: 0;
  margin-left: -10px;
}

:deep(.el-table__body tr > td:hover) {

  :deep(.el-input__wrapper),
  :deep(.el-select__wrapper) {
    box-shadow: 0 0 0 1px #888 inset;
  }
}

:deep(.el-table__body tr:hover > td) {
  background-color: transparent !important;
  /* 移除背景颜色 */
}

:deep(.el-table__body tr > td) {
  height: 32px;
  line-height: 32px;
  padding: 0;

  .cell {
    padding: 0;
  }
}

:deep(.el-table td.el-table__cell div) {
  /* display: flex; */
  align-items: center;
}

:deep(.el-table__body-wrapper) {
  height: calc(100% - 40px) !important;
}

:deep(.frist.el-table--default .cell) {
  display: flex !important;
}
</style>
